package com.eight.group.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.eight.group.entity.PageResult;
import com.eight.group.entity.QueryPageBean;
import com.eight.group.mapper.RoleMapper;
import com.eight.group.pojo.CheckItem;
import com.eight.group.pojo.Permission;
import com.eight.group.pojo.Role;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.xqx.eight.group.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service(interfaceClass = RoleService.class)
public class RoleServiceImpl implements RoleService {

    @Autowired
    private RoleMapper roleMapper;

    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {

        //分页助手参数设置
        PageHelper.startPage(queryPageBean.getCurrentPage(), queryPageBean.getPageSize());

        List<Role> list = roleMapper.findPageByCondition(queryPageBean.getQueryString());

        //返回封装后的结果
        return new PageResult(new PageInfo<>(list).getTotal(), list);
    }


    @Override
    public Role findById(Integer id) {

        return roleMapper.findById(id);

    }


    //修改权限
    @Override
    @Transactional
    public void changePermissions(Role role, Integer[] permissionIds) {
        //根据role_id删除t_role_Permission表数据
        roleMapper.deleteRoleAndPermissionByRoleId(role.getId());

        //重新往t_role_Permission表添加数据
        if (role.getId() != null && permissionIds.length > 0) {
            this.setRoleAndPermission(role.getId(), permissionIds);
        }
    }

    //添加角色
    @Override
    @Transactional
    public void add(Role role, Integer[] permissionIds) {

        roleMapper.add(role);

        if (role.getId() != null && permissionIds.length > 0) {
            this.setRoleAndPermission(role.getId(), permissionIds);
        }
    }

    /**
     * 删除角色和用户与角色关系
     * @param id  role_id
     */
    @Override
    @Transactional
    public void delete(Integer id) {
        roleMapper.deleteUserAndRoleByRoleId(id);
        roleMapper.deleteRoleAndPermissionByRoleId(id);
        roleMapper.delete(id);
    }

    @Override
    public PageResult findAll() {
        //调用mapper查询
        List<Role> list = roleMapper.findPageByCondition(null);

        list.forEach(s-> System.out.println(s));
        //放回封装后的结果
        return new PageResult(null,list);
    }


    /**
     * 设置 角色与权限 关联
     *
     * @param roleId        角色
     * @param permissionIds 权限们
     */

    private void setRoleAndPermission(int roleId, Integer[] permissionIds) {
        HashMap<String, Object> map = new HashMap<>(2);
        map.put("roleId", roleId);
        map.put("permissionIds", permissionIds);
        roleMapper.setRoleAndPermission(map);
    }


}
